package controller;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.io.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pojo.Archive;
import service.ArchiveService;
import service.UserLogService;

@Controller
public class ArchiveController {
	 ArchiveService service = new ArchiveService();
	 UserLogService service1 = new UserLogService();
	@RequestMapping(value = "/add.action", method = RequestMethod.POST)
	@ResponseBody
	public String add(
			@CookieValue(value = "user", defaultValue = "") String user_id,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		    service.add(archive_id, identity, name, gender, birthday, date_retire1,
				        date_retire2, sp, fc, title, seniority);
		    Map<String,Object> map=service.lastid();
		    service1.adduser_log(user_id,map.get("id").toString(), "添加数据");
		    return "OK";
	}
	// 查询精准一条
	@RequestMapping(value = "/queryone.action", method = RequestMethod.POST)
	@ResponseBody
	public String queryone(
			@CookieValue(value = "user", defaultValue = "") String id,
			@RequestParam(value = "search", defaultValue = "") String search,
			HttpServletResponse response) {
		    List<Archive> map = service.queryone(search);
		    if (0 == map.size()) {
			return "REE";
   }        else if (1 < map.size()) {
			return "REE2";
}
		    service1.adduser_log(id, String.valueOf(map.get(0).getId()),"浏览信息");
		    return String.valueOf(map.get(0).getId());
	}
	// 将查出那条显示出来
	@RequestMapping(value = "/query.action", method = RequestMethod.GET)
	@ResponseBody
	public Archive query(
			@CookieValue(value = "user", defaultValue = "") String userid,
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		    ArchiveService service = new ArchiveService();
		    Archive map = service.query(id);
		    UserLogService service1 = new UserLogService();
		    service1.adduser_log(userid,String.valueOf(map.getId()), "浏览信息");
		    return map;
	}
	// 修改数据并记录
	@RequestMapping(value = "/update.action", method = RequestMethod.POST)
	@ResponseBody
	public String update(
			@CookieValue(value = "user", defaultValue = "") String user_id,
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "archive", defaultValue = "") String archive,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			HttpServletResponse response) {
		    service.update(id, identity, name, gender, birthday, date_retire1,
				           date_retire2, sp, fc, title, seniority);
		    service1.adduser_log(user_id, id, "修改数据");
		    return "OK";
	}
	// 上传文件
	@RequestMapping(value = "/{id}/upload.action", method = RequestMethod.POST)
	@ResponseBody
	public String upload(
			@CookieValue(value = "user", defaultValue = "") String user_id,
			@PathVariable String id,
			@RequestParam("file") MultipartFile file, HttpServletRequest req) {
	     if (file.isEmpty()) {
			System.out.println("未选择文件");
			return "ERROR_NO_FILE";
		}
	    try {
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			String fileExtension = fileName
					.substring(fileName.lastIndexOf(".") + 1);
			String newFileName = String.valueOf(System.currentTimeMillis())
					+ "." + fileExtension;
			System.out.printf("id: %s\r\n", id);
			Archive archive = service.query(id);
			String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
					.getServletContext().getRealPath("/"), "upload", archive
					.getArchive().toString(), newFileName);
			System.out.printf("filePath: %s\r\n", filePath);
			File existsFile = new File(filePath);
		if (!existsFile.getParentFile().exists()) {
		if (!existsFile.getParentFile().mkdirs()) {
		    System.out.println("创建目录失败");
		    return "ERROR_ON_MKDIR";
 }
}
		if (existsFile.exists()) {
		if (existsFile.delete()) {
    }   else {
					System.out.println("删除文件失败：" + filePath);
	}
}
			BufferedOutputStream stream = new BufferedOutputStream(
	        new FileOutputStream(new File(filePath)));
			System.out.println("befor write");
			stream.write(bytes);
			System.out.println("after write");
			stream.close();
			service1.addfile(String.valueOf(archive.getId()), newFileName);
			System.out.println("上传文件成功：" + filePath);
			service1.adduser_log(user_id,id, "上传文件");
			return "OK";
    } catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
	}
}
	// 查询文件的详细信息
	@RequestMapping(value = "/queryword.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> queryword(
			@CookieValue(value = "user", defaultValue = "") String user_id,
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletResponse response) {
		    List<Map> map = service.queryword(id);
		    //System.out.println(map);
		    service1.adduser_log(user_id,id, "浏览信息");
		    return map;
}
	@RequestMapping(value = "/querydel.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map> querydel(
			@RequestParam(value = "id", defaultValue = "") String id) {
		    List<Map> map = service.querydel(id);
		    return map;
	}
 // 删除数据库以及服务器里的文件
	@RequestMapping(value = "/deletephoto.action", method = RequestMethod.POST)
	@ResponseBody
	public String deletephoto(
			@CookieValue(value = "user", defaultValue = "") String user_id,
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletRequest req) {
		    List<Map> map = service.querydel(id);
		    // System.out.printf("file data: %s\r\n", map.get(0));
		    // Archive archive = service.query(map.get(0).get("aid").toString());
		    String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
				   .getServletContext().getRealPath("/"), "upload", map.get(0)
				   .get("archive_id").toString(), map.get(0).get("name")
				   .toString());
		    // System.out.printf("filePath: %s\r\n", filePath);
		    File existsFile = new File(filePath);
		    existsFile.delete();
		    service.deletephoto(id);
		    service1.adduser_log(user_id,map.get(0).get("aid").toString(), "删除文件");
		    return "OK";
}
	//   模糊查询 
	@RequestMapping(value="/querymohu.action",method=RequestMethod.POST)	
	@ResponseBody
    public List<Map> querymohu(
	    	@CookieValue(value = "user", defaultValue = "") String user_id,
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "archive", defaultValue = "") String archive,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
	        HttpServletResponse response){
		    List<Map> map=service.querymohu(id, archive, identity, name, gender, birthday, date_retire1, date_retire2, sp, fc, title, seniority);
		    service1.adduser_log(user_id,map.get(0).get("id").toString(), "浏览信息");
		    return map;
	}               
	//最近预览的四条档案
	@RequestMapping(value="querylist.action",method=RequestMethod.GET)	
	@ResponseBody
    public List<Map> querylist( 
		   @CookieValue(value="user",defaultValue="")String userId,
	       HttpServletResponse response){
		   List<Map> map=service.querylist(userId);
		   return map;     
	}                 
	//最近添加的四条档案
	@RequestMapping(value="querylistadd.action",method=RequestMethod.GET)	
	@ResponseBody
	    public List<Map> querylistadd( 
		   @CookieValue(value="user",defaultValue="")String userId,
	       HttpServletResponse response){
		   //System.out.println(userId);
		   List<Map> map=service.querylistadd(userId);
		   return map;     
	}                
	//统计每个用户上传的档案总数
	@RequestMapping(value = "/querycount.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Map> querycount(
	      @CookieValue(value = "user", defaultValue = "") String userId,
	      @RequestParam(value = "date1", defaultValue = "") String date1,
		  @RequestParam(value = "date2", defaultValue = "") String date2,
		  HttpServletResponse response ){
		  List<Map> list=service.querycount(date1,date2);
		  return list;
	}

}
